<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="names" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.names }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="bj(item, index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      flag: false,
      names: "",
      age: 0,
      gender: "",
      arr: [],
      ins: -1,
    };
  },
  computed: {},
  watch: {},
  created() {},
  methods: {
    add() {
      if (
        this.names.trim() === "" ||
        this.age <= 0 ||
        this.gender.trim() === ""
      )
        return alert("内容不符合条件！");

      if (this.flag === true) {
        this.arr[this.ins].names = this.names;
        this.arr[this.ins].age = this.age;
        this.arr[this.ins].gender = this.gender;
        this.flag = false;
      } else {
        this.arr.push({
          names: this.names,
          age: this.age,
          gender: this.gender,
        });
      }

      this.names = "";
      this.age = 0;
      this.gender = "";
    },
    bj(item, index) {
      if (this.flag === false) {
        this.names = item.names;
        this.age = item.age;
        this.gender = item.gender;
        this.ins = index;
        console.log(this.ins);
        this.flag = true;
      }
    },
    del(index) {
      this.arr.splice(index, 1);
    },
  },
};
</script>
